import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import '../common.dart';

RxList listItem = [].obs;

List items = [
  {'text': "全部", "index": 0},
  {'text': "待付款", "index": 1},
  {'text': "已完成", "index": 2},
  {'text': "已取消", "index": 3},
];

List<Map> items1 = [
  {'text': "全部", "index": 0},
  {'text': "寄售中", "index": 1},
  {'text': "已售出", "index": 2},
  {'text': "已取消", "index": 3},
];
List<Map> items2 = [
  {'text': "全部", "index": 0},
  {'text': "委托中", "index": 1},
  {'text': "已完成", "index": 2},
];
List<Map> items3 = [
  {'text': "全部", "index": 0},
  {'text': "竞价中", "index": 1},
  {'text': "已完成", "index": 2},
];

RxInt _index = 0.obs;
RxInt index = 0.obs;
RxList listData = [].obs;

getOrderList(url, status) {
  // 订单
  getData(
    url: url,
    data: {"status": status, "per_page": '900', 'page': '1'},
  ).then((res) {
    if (res != null) {
      // List<String> parts = dateStr.split(' ');
      // List<String> dateParts = parts[0].split('-');
      // List<String> timeParts = parts[1].split(':');

      // DateTime dt = DateTime(
      //   int.parse(dateParts[0]), // 年
      //   int.parse(dateParts[1]), // 月
      //   int.parse(dateParts[2]), // 日
      //   int.parse(timeParts[0]), // 时
      //   int.parse(timeParts[1]), // 分
      //   int.parse(timeParts[2])  // 秒
      // );

      //  DateTime targetTime = DateTime(2025, 6, 11, 17, 43, 58);
      //        int milliseconds = targetTime.millisecondsSinceEpoch;

      for (var i = 0; i < res['list'].length; i++) {
        if (res['list'][i]['auto_closed_at'] != null) {
          List<String> parts = res['list'][i]['auto_closed_at'].split(' ');
          List<String> dateParts = parts[0].split('-');
          List<String> timeParts = parts[1].split(':');

          final targetTime = DateTime(
            int.parse(dateParts[0]), // 年
            int.parse(dateParts[1]), // 月
            int.parse(dateParts[2]), // 日
            int.parse(timeParts[0]), // 时
            int.parse(timeParts[1]), // 分
            int.parse(timeParts[2]), // 秒
          );

          int currentSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;

          int milliseconds = targetTime.millisecondsSinceEpoch ~/ 1000;

          res['list'][i]['created'] = milliseconds - currentSeconds;
        }
      }

      listData.value = res['list'];
    }
  });
}

class OrderList extends StatefulWidget {
  const OrderList({super.key});
  @override
  State<OrderList> createState() => _HomePageState();
}

class _HomePageState extends State<OrderList>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  offOrder(item, key) {
    Get.dialog(
      AlertDialog(
        backgroundColor: Colors.transparent,
        content: Stack(
          children: [
            Image.asset('static/tan.png', width: 250, fit: BoxFit.fitWidth),
            Positioned(
              top: 80,
              left: 0,
              right: 0,
              child: Align(
                child: Column(
                  children: [
                    Text(
                      '提示',
                      style: TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 15),
                    Text(
                      '确定取消订单吗',
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        if (index.value == 0) {
                          postData(url: '/order/change/${item['uuid']}').then((
                            res,
                          ) {
                            if (res != null) {
                              Get.back();
                              showTost('取消成功');
                              listData[key]['status'] = 2;
                              listData[key]['union_status_text'] = '已关闭';
                              listData.refresh();
                            }
                          });
                        }
                        if (index.value == 1) {
                          postData(url: '/resale/close/${item['uuid']}').then((
                            res,
                          ) {
                            if (res != null) {
                              Get.back();
                              showTost('取消成功');
                              listData[key]['status'] = 4;
                              listData[key]['statusValue'] = '已取消';
                              listData.refresh();
                            }
                          });
                        }
                        if (index.value == 2) {
                          postData(
                            url: '/want/cancel/',
                            data: {'want_id': '${item['id']}'},
                          ).then((res) {
                            if (res != null) {
                              Get.back();
                              showTost('取消成功');
                              listData[key]['status'] = 2;
                              listData[key]['union_status_text'] = '已取消';
                              listData.refresh();
                            }
                          });
                        }
                        if (index.value == 3) {
                          postData(
                            url: '/bidding/cancel',
                            data: {'bidding_id': '${item['id']}'},
                          ).then((res) {
                            if (res != null) {
                              Get.back();
                              showTost('取消成功');
                              listData[key]['status'] = 2;
                              listData[key]['union_status_text'] = '已取消';
                              listData.refresh();
                            }
                          });
                        }
                      },
                      child: Container(
                        height: 50,
                        margin: EdgeInsets.only(top: 50, bottom: 30),
                        alignment: Alignment.center,
                        width: 210,
                        decoration: BoxDecoration(
                          color: Color(0XFF0F172B),
                          borderRadius: BorderRadius.circular(50),
                        ),
                        child: Text(
                          '确认',
                          style: TextStyle(
                            fontSize: 16,
                            color: Color(0XFFFFFFFF),
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () => {Get.back()},
                      child: Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      print('object');
      getOrderList('/order/list', 'all');

      listItem.value = items;
    });
    _startTimer();
  }

  int _totalSeconds = 300; // 5分钟 = 300秒
  late Timer _timer;

  void _startTimer() {
    const oneSec = Duration(seconds: 1);
    _timer = Timer.periodic(oneSec, (Timer timer) {
      if (_totalSeconds == 0) {
        timer.cancel();
      } else {
        setState(() {
          _totalSeconds--;
        });
      }
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    int minutes = (_totalSeconds ~/ 60);
    int seconds = (_totalSeconds % 60);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xffffffff),
        title: Text(
          '藏品订单',
          style: TextStyle(color: Color(0XFF0F172B), fontSize: 18),
        ),
        leading: buildBackButton(context),
        centerTitle: true,
        bottom: TabBar(
          onTap:
              (vlaue) => {
                _index.value = 0,
                index.value = vlaue,
                listData.value = [],
                if (vlaue == 0)
                  {getOrderList('/order/list', 'all'), listItem.value = items}
                else if (vlaue == 1)
                  {
                    getOrderList('/resale/my_list', 'all'),
                    listItem.value = items1,
                  }
                else if (vlaue == 2)
                  {getOrderList('/want/orders', 'all'), listItem.value = items2}
                else
                  {
                    getOrderList('/bidding/orders', 'all'),
                    listItem.value = items3,
                  },
              },
          indicatorColor: Color(0XFF0F172B),
          indicatorWeight: 3.0,
          labelPadding: EdgeInsets.symmetric(vertical: 10),
          indicatorSize: TabBarIndicatorSize.tab,
          labelColor: Color(0XFF0F172B),
          unselectedLabelColor: Color(0xff999999),
          dividerColor: Color(0XFFF8F9FD),
          dividerHeight: 4,
          controller: _tabController,
          overlayColor: WidgetStateProperty.all(Colors.transparent),
          tabs: [
            Text('我的订单', style: TextStyle(fontSize: 14)),
            Text('我的寄售', style: TextStyle(fontSize: 14)),
            Text('我的委托', style: TextStyle(fontSize: 14)),
            Text('我的竞价', style: TextStyle(fontSize: 14)),
          ],
        ),
      ),
      body: Obx(
        () => ListView(
          padding: EdgeInsets.only(top: 20),
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children:
                  listItem
                      .map(
                        (item) => GestureDetector(
                          onTap: () {
                            _index.value = item['index'];
                            if (index.value == 0) {
                              if (item['index'] == 0) {
                                getOrderList('/order/list', 'all');
                              } else if (item['index'] == 1) {
                                getOrderList('/order/list', 'pay_pending');
                              } else if (item['index'] == 2) {
                                getOrderList('/order/list', 'pay_ok');
                              } else if (item['index'] == 3) {
                                getOrderList('/order/list', 'close');
                              }
                            } else if (index.value == 1) {
                              if (item['index'] == 0) {
                                getOrderList('/resale/my_list', 'all');
                              } else if (item['index'] == 1) {
                                getOrderList('/resale/my_list', 'pending');
                              } else if (item['index'] == 2) {
                                getOrderList('/resale/my_list', 'completed');
                              } else if (item['index'] == 3) {
                                getOrderList('/resale/my_list', 'closed');
                              }
                            } else if (index.value == 2) {
                              if (item['index'] == 0) {
                                getOrderList('/want/orders', 'all');
                              } else if (item['index'] == 1) {
                                getOrderList('/want/orders', 'wait_want');
                              } else if (item['index'] == 2) {
                                getOrderList('/want/orders', 'deal');
                              }
                            } else if (index.value == 3) {
                              if (item['index'] == 0) {
                                getOrderList('/bidding/orders', 'all');
                              } else if (item['index'] == 1) {
                                getOrderList('/bidding/orders', 'wait_bidding');
                              } else if (item['index'] == 2) {
                                getOrderList('/bidding/orders', 'deal');
                              }
                            }
                          },
                          child: Container(
                            margin: EdgeInsets.only(left: 15),
                            height: 28,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color:
                                  _index.value == item['index']
                                      ? Color(0XFF0F172B)
                                      : Color(0XFFF8F9FD),
                              borderRadius: BorderRadius.circular(28),
                            ),
                            padding: EdgeInsets.symmetric(horizontal: 15),
                            child: Text(
                              item['text'],
                              style: TextStyle(
                                fontSize: 12,
                                color:
                                    _index.value == item['index']
                                        ? Color(0XFFffffff)
                                        : Color(0XFF0F172B),
                              ),
                            ),
                          ),
                        ),
                      )
                      .toList(),
            ),
            if (listData.isEmpty) isdata(),
            for (var item in listData.asMap().entries)
              GestureDetector(
                onTap:
                    () => {
                      // toNamed('/web_tabs/order/consignment_detail')
                    },
                child: Container(
                  margin: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                  padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                  decoration: BoxDecoration(
                    color: Color(0XFFF8F9FD),
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Text(
                                '订单编号:',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Color(0XFF0F172B),
                                ),
                              ),
                              Text(
                                item.value['resale_type'] == 'package_sku'
                                    ? '寄售 '
                                    : item.value['resale_type'] == 'to_user'
                                    ? '转售 '
                                    : item.value['resale_type'] ==
                                        'package_bidding'
                                    ? '竞价 '
                                    : item.value['resale_type'] ==
                                        'package_want'
                                    ? '委托 '
                                    : '',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Color.fromARGB(255, 40, 120, 255),
                                ),
                              ),
                              Text(
                                '${item.value['number'] ?? item.value['no']}:',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Color(0XFF0F172B),
                                ),
                              ),
                            ],
                          ),
                          // Text(
                          //   item.value['resale_type']=='package_sku'?
                          //     '订单编号:寄售${item.value['number'] ?? item.value['no']}':
                          //     '订单编号:转售 ${item.value['number'] ?? item.value['no']}'
                          //     ,
                          //     style: TextStyle(
                          //         fontSize: 12,
                          //         color: Color(0XFF0F172B)))

                          //         :
                          // Text(
                          //     '订单编号:${item.value['number'] ?? item.value['no']}',
                          //     style: TextStyle(
                          //         fontSize: 12,
                          //         color: Color(0XFF0F172B))),
                          Text(
                            '${item.value['union_status_text'] ?? item.value['statusValue']}',
                            style: TextStyle(
                              fontSize: 12,
                              color: Color(0XFF0F172B),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 10),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(10.0), // 设置圆角大小
                            child: Image.network(
                              '${item.value['thumb']}',
                              width: 80,
                              height: 80,
                              fit: BoxFit.fill,
                              errorBuilder: (context, error, stackTrace) {
                                return SizedBox(width: 80);
                              },
                            ),
                          ),
                          SizedBox(width: 10),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '${item.value['title']}',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Color(0XFF0F172B),
                                ),
                              ),
                              SizedBox(height: 35),
                              Row(
                                children: [
                                  Text(
                                    '￥',
                                    style: TextStyle(
                                      fontSize: 11,
                                      color: Color(0XFF0F172B),
                                    ),
                                  ),
                                  if (index.value == 2)
                                    Text(
                                      '${item.value['order_money_price'] / 100}',
                                      style: TextStyle(
                                        fontSize: 16,
                                        color: Color(0XFF0F172B),
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  if (index.value == 0)
                                    Text(
                                      '${item.value['order_money_price'] / 100}',
                                      style: TextStyle(
                                        fontSize: 16,
                                        color: Color(0XFF0F172B),
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  if (index.value == 1 || index.value == 3)
                                    Text(
                                      '${item.value['money_price'] / 100}',
                                      style: TextStyle(
                                        fontSize: 16,
                                        color: Color(0XFF0F172B),
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                ],
                              ),
                            ],
                          ),
                          Expanded(child: SizedBox()),
                          if (index.value == 0)
                            Container(
                              margin: EdgeInsets.only(top: 5),
                              child: Text(
                                'x${item.value['total']}',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Color(0XFF0F172B),
                                ),
                              ),
                            ),
                          if (index.value == 2)
                            Container(
                              margin: EdgeInsets.only(top: 5),
                              child: Text(
                                '${item.value['ok_count']}/${item.value['sku_total']}',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Color(0XFF0F172B),
                                ),
                              ),
                            ),
                        ],
                      ),
                      SizedBox(height: 10),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '创建时间',
                            style: TextStyle(
                              fontSize: 12,
                              color: Color(0XFF999999),
                            ),
                          ),
                          Text(
                            '${item.value['created_at']}',
                            style: TextStyle(
                              fontSize: 12,
                              color: Color(0XFF0F172B),
                            ),
                          ),
                        ],
                      ),

                      if (item.value['status'] == 1 && index.value != 1)
                        Container(
                          padding: EdgeInsets.only(top: 10),
                          margin: EdgeInsets.only(top: 10),
                          decoration: BoxDecoration(
                            border: Border(
                              top: BorderSide(color: Color(0XFFDDDDDD)),
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              if (item.value['created'] > 0)
                                MinuteSecondCountdown(
                                  initialSeconds: item.value['created'],
                                  textStyle: TextStyle(
                                    fontSize: 16,
                                    color: Colors.red,
                                  ),
                                  onComplete: () {
                                    item.value['created'] = 0;
                                    item.value['status'] = 2;
                                    item.value['union_status_text'] = '已关闭';
                                    listData.refresh();
                                  },
                                ),
                              Expanded(child: SizedBox()),
                              GestureDetector(
                                onTap: () {
                                  offOrder(item.value, item.key);
                                },
                                child: Text(
                                  '取消',
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Color(0XFF0F172B),
                                  ),
                                ),
                              ),
                              SizedBox(width: 30),
                              Container(
                                height: 25,
                                width: 50,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: Color(0XFF0F172B),
                                  borderRadius: BorderRadius.circular(25),
                                ),
                                child: GestureDetector(
                                  onTap: () {
                                    postData(
                                      url:
                                          '/order/payment-config/${item.value['uuid']}',
                                      data: {
                                        "url":
                                            'back.html?app=1&back=two&web=back',
                                      },
                                    ).then((res) {
                                      if (res != null) {
                                        if (kIsWeb) {
                                          final uur = Uri.parse(
                                            '${res['pay_url']}',
                                          );
                                          launchUrl(
                                            uur,
                                            webOnlyWindowName: '_self',
                                          );
                                        } else {
                                          toNamed(
                                            '/webview?url=${res['pay_url']}&back=suu',
                                          );
                                        }
                                      }
                                    });
                                  },
                                  child: Text(
                                    '付款',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Color(0XFFFFFFFF),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),

                      if (item.value['status'] == 1 && index.value == 1)
                        Container(
                          padding: EdgeInsets.only(top: 15),
                          margin: EdgeInsets.only(top: 15),
                          decoration: BoxDecoration(
                            border: Border(
                              top: BorderSide(color: Color(0XFFDDDDDD)),
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  offOrder(item.value, item.key);
                                },
                                child: Text(
                                  '取消',
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Color(0XFF0F172B),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),

                      if (item.value['status'] == 7 && index.value == 2)
                        Container(
                          padding: EdgeInsets.only(top: 15),
                          margin: EdgeInsets.only(top: 15),
                          decoration: BoxDecoration(
                            border: Border(
                              top: BorderSide(color: Color(0XFFDDDDDD)),
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  offOrder(item.value, item.key);
                                },
                                child: Text(
                                  '取消',
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Color(0XFF0F172B),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      if (item.value['status'] == 7 && index.value == 3)
                        Container(
                          padding: EdgeInsets.only(top: 15),
                          margin: EdgeInsets.only(top: 15),
                          decoration: BoxDecoration(
                            border: Border(
                              top: BorderSide(color: Color(0XFFDDDDDD)),
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  offOrder(item.value, item.key);
                                },
                                child: Text(
                                  '取消',
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Color(0XFF0F172B),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),

                      // Container(
                      //   padding: EdgeInsets.only(top: 15),
                      //   margin: EdgeInsets.only(top: 15),
                      //   decoration: BoxDecoration(
                      //     border: Border(top: BorderSide(color: Color(0XFFDDDDDD)))
                      //   ),
                      //   child:  Row(
                      //   mainAxisAlignment: MainAxisAlignment.end,
                      //   children: [
                      //     Text('取消',
                      //         style: TextStyle(
                      //             fontSize: 12, color: Color(0XFF0F172B))),
                      //     SizedBox(
                      //       width: 30,
                      //     ),
                      //     Container(
                      //         height: 25,
                      //         width: 50,
                      //         alignment: Alignment.center,
                      //         decoration: BoxDecoration(
                      //             color: Color(0XFF0F172B),
                      //             borderRadius: BorderRadius.circular(25)),
                      //         child: GestureDetector(
                      //           onTap: () => {
                      //             toNamed(
                      //                 '/web_tabs/order/pending_payment')
                      //           },
                      //           child: Text('付款',
                      //               style: TextStyle(
                      //                   fontSize: 12,
                      //                   color: Color(0XFFFFFFFF))),
                      //         ))
                      //   ],
                      // ),
                      // )
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

class MinuteSecondCountdown extends StatefulWidget {
  final int initialSeconds;
  final TextStyle? textStyle;
  final VoidCallback? onComplete;
  final String? completeText;

  const MinuteSecondCountdown({
    Key? key,
    required this.initialSeconds,
    this.textStyle,
    this.onComplete,
    this.completeText,
  }) : super(key: key);

  @override
  _MinuteSecondCountdownState createState() => _MinuteSecondCountdownState();
}

class _MinuteSecondCountdownState extends State<MinuteSecondCountdown> {
  late int _remainingSeconds;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    _remainingSeconds = widget.initialSeconds;
    _startTimer();
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_remainingSeconds > 0) {
          _remainingSeconds--;
        } else {
          _timer.cancel();
          widget.onComplete?.call();
        }
      });
    });
  }

  String _formatTime(int seconds) {
    if (seconds <= 0 && widget.completeText != null) {
      return widget.completeText!;
    }

    final minutes = (seconds ~/ 60).toString().padLeft(2, '0');
    final remainingSeconds = (seconds % 60).toString().padLeft(2, '0');
    return '$minutes:$remainingSeconds';
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      _formatTime(_remainingSeconds),
      style:
          widget.textStyle ??
          const TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
            color: Colors.blue,
          ),
    );
  }
}
